package com.ruoyi.eqmonitor.dispose.task;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.ruoyi.common.redis.service.RedisService;
import com.ruoyi.eqmonitor.dispose.mapper.MonitorDataIotDBMapper;
import com.ruoyi.eqmonitor.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Profile;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.*;

@Slf4j
@Component
//@Profile("prod")
public class AnalyseTask {
    @Resource
    private RedisService redisService;
    @Resource
    private IOptDeviceMonitorAnalyseDataService iOptDeviceMonitorAnalyseDataService;

    @Scheduled(cron = "1 1 0/1 * * ?")
    public void analyseTerminalTask() {
        try {
            DateTime today = DateUtil.endOfDay(new Date());
            // 处理日累计
            iOptDeviceMonitorAnalyseDataService.analyseDailyAccumulation(today, true);

            // 2023-12-19 判断今天是否还有别的日期数据回传
            // 先从redis中获取
            Map<String, Object> cacheMap = redisService.getCacheMap(MonitorDataIotDBMapper.TODAY_MONITOR_DATE_REDIS_KEY);

            // 如果为空，直接返回
            if(MapUtil.isEmpty(cacheMap)) return;
            Set<String> dates = cacheMap.keySet();
            for (String date : dates) {
                DateTime parse = StrUtil.isEmpty(date) ? null : DateUtil.parse(date, "yyyy-MM-dd");
                // 不处理null和今天以后的数据
                if (parse == null || parse.isAfter(today) || DateUtil.isSameDay(today, parse)) continue;
                // 处理日累计
                iOptDeviceMonitorAnalyseDataService.analyseDailyAccumulation(DateUtil.offsetDay(parse, 1), false);
                // 删除redis中的回传日期, 表示已经执行过分析
                redisService.deleteCacheMapValue(MonitorDataIotDBMapper.TODAY_MONITOR_DATE_REDIS_KEY, date);
            }
        } catch (Exception e) {
            log.error("日累计定时任务执行失败", e);
        }
    }

}
